package com.mogist.hqc.module.order.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.view.View
import butterknife.OnClick
import butterknife.Optional
import com.alipay.sdk.app.PayTask
import com.mogist.hqc.R
import com.mogist.hqc.alipay.PayResult
import com.mogist.hqc.base.BaseMVPActivity
import com.mogist.hqc.entitys.BaseModel
import com.mogist.hqc.entitys.response.OrderVo
import com.mogist.hqc.entitys.response.WXDto
import com.mogist.hqc.module.order.contract.OrderPayContract
import com.mogist.hqc.module.order.presenter.OrderPayPresenter
import com.mogist.hqc.mvp.HttpDto
import com.mogist.hqc.util.Constant
import com.tencent.mm.opensdk.modelpay.PayReq
import kotlinx.android.synthetic.main.activity_order_pay.*
import kotlinx.android.synthetic.main.include_title.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import talex.zsw.basecore.util.JsonTool
import talex.zsw.basecore.util.LogTool
import talex.zsw.basecore.util.TextTool
import talex.zsw.basecore.util.TimeTool
import talex.zsw.basecore.view.dialog.sweetalertdialog.SweetAlertDialog
import talex.zsw.basecore.view.other.RxToast

/**
 * 作用：订单支付
 * 作者：赵小白 email:vvtale@gmail.com  
 * 修改人：
 * 修改时间：
 * 修改备注：
 */
class OrderPayActivity : BaseMVPActivity<OrderPayContract.Presenter>(), OrderPayContract.View
{
    var order: OrderVo? = null
    var payType = "ALIPAY"
    override fun initArgs(intent: Intent)
    {
        intent.getSerializableExtra("order")
                ?.let {
                    order = it as OrderVo
                }
    }

    override fun initView()
    {
        setContentView(R.layout.activity_order_pay)
        mPresenter = OrderPayPresenter(this)
    }

    @SuppressLint("SetTextI18n")
    override fun initData()
    {
        mTitleBar.setTitle("订单支付")
        mTitleBar.setBackOnclickListener { exit() }
        TextTool.getBuilder("￥")
                .append(order!!.amountAll)
                .setProportion(2F)
                .into(mTvPrice)
        mTvTime.text =
                "请于 ${TimeTool.changeFormat(order!!.payOverTime,
                                            "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
                                            TimeTool.STR_FOMATER_DATA_TIME)} 前完成支付"
    }

    @Optional
    @OnClick(R.id.mTvSure, R.id.mLLZFB, R.id.mLLWX)
    fun onViewClicked(view: View)
    {
        if (!isFastClick)
        {
            when (view.id)
            {
                R.id.mTvSure ->
                { // 支付
                    val body = BaseModel(true)
                    body.orderNo = order!!.orderNo
                    body.payType = payType
                    mPresenter.getData(HttpDto(Constant.ORDER_PAY,
                                               body).setTryAgain(true).setErrorTitle("支付失败"))
                }
                R.id.mLLZFB  ->
                {
                    payType = "ALIPAY"
                    mIvZFB.setImageResource(R.drawable.i_choose)
                    mIvWX.setImageResource(R.drawable.i_unchoose)
                }
                R.id.mLLWX   ->
                {
                    payType = "WECHAT"
                    mIvZFB.setImageResource(R.drawable.i_unchoose)
                    mIvWX.setImageResource(R.drawable.i_choose)
                }
            }
        }
    }

    override fun onBackPressed()
    {
        exit()
    }

    private fun exit()
    {
        showDialog(SweetAlertDialog.NORMAL_TYPE, "是否放弃支付？", "", "是", "否", {
            disDialog()
            finish()
        }, null)
    }

    override fun bindPayStr(str: String)
    {
        if (payType == "ALIPAY")
        {
            alipay(str)
        }
        else
        {
            wxPay(JsonTool.getObject(str, WXDto::class.java))
        }
    }

    private fun paySuccess()
    {
        val body = BaseModel(true)
        body.orderNo = order!!.orderNo
        body.payType = payType
        mPresenter.getData(HttpDto(Constant.ORDER_NOTIFY, body).setTryAgain(true).setErrorTitle("通知后台刷新支付状态失败"))
    }

    override fun notifySuccess()
    {
        disDialog()
        val intent = Intent(this@OrderPayActivity, OrderPayResultActivity::class.java)
        start(intent)
        finish()
    }

    // --------------- 支付宝 ---------------
    private val SDK_PAY_FLAG = 1
    private val SDK_CHECK_FLAG = 2

    fun alipay(SRA: String)
    {
        val payRunnable = Runnable {
            // 构造PayTask 对象
            val alipay = PayTask(this@OrderPayActivity)
            // 调用支付接口，获取支付结果
            val result = alipay.pay(SRA, true)
            val msg = Message()
            msg.what = SDK_PAY_FLAG
            msg.obj = result
            mHandler.sendMessage(msg)
        }
        // 必须异步调用
        val payThread = Thread(payRunnable)
        payThread.start()
    }

    private val mHandler = object : Handler()
    {
        override fun handleMessage(msg: Message)
        {
            LogTool.nv("msg.what = " + msg.what)
            when (msg.what)
            {
                SDK_PAY_FLAG   ->
                {
                    val payResult = PayResult(msg.obj as String)
                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    val resultInfo = payResult.result
                    val resultStatus = payResult.resultStatus
                    LogTool.nv("resultStatus = $resultStatus")
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000"))
                    {
                        EventBus.getDefault()
                                .post(Constant.EVENT_PAY_SUCCESS)
                        EventBus.getDefault()
                                .post(Constant.EVENT_REFRESH_ORDER)
                    }
                    else
                    {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000"))
                        {
                            showDialog(SweetAlertDialog.WARNING_TYPE, "支付失败!", "支付结果确认中")
                        }
                        else
                        {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            showDialog(SweetAlertDialog.ERROR_TYPE, "支付失败!", "用户主动取消支付")
                        }
                    }
                }
                SDK_CHECK_FLAG ->
                {
                    showDialog(SweetAlertDialog.ERROR_TYPE, "支付失败!", "检查结果为：" + msg.obj)
                }
                else           ->
                {
                }
            }
        }
    }

    // --------------- 微信 ---------------
    private fun wxPay(dto: WXDto)
    {
        try
        {
            val req = PayReq()
            req.appId = dto.appid.trim()
            req.partnerId = dto.partnerid.trim()
            req.prepayId = dto.prepayid.trim()
            req.nonceStr = dto.noncestr.trim()
            req.timeStamp = dto.timestamp.trim()
            req.packageValue = dto.packageX.trim()
            req.sign = dto.sign
            val flag = mApplication.wxApi.sendReq(req)
            LogTool.ne("flag=$flag")
        }
        catch (e: Exception)
        {
            disDialog()
            RxToast.error("请求微信支付失败，请稍后重试")
            e.printStackTrace()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(event: String)
    {
        if (event == Constant.EVENT_PAY_SUCCESS)
        {
            paySuccess()
        }
        if (event == Constant.EVENT_PAY_FAILED)
        {
            disDialog()
        }
    }

}